package cac.fenjian.resource.workbinMaterialMaintain.rest;

import cac.fenjian.resource.MsWorkbinBasic.dto.MsWorkbinBasicDTO;
import cac.fenjian.resource.workbinMaterialMaintain.dao.workbinMaterialMaintainDao;
import cac.fenjian.resource.workbinMaterialMaintain.service.workbinMaterialMaintainService;
import com.alibaba.fastjson.JSON;
import com.cac.dme.adapter.rest.msg.PageParameter;
import com.cac.dme.adapter.rest.msg.QueryReqBean;
import com.cac.dme.adapter.rest.msg.QueryRespBean;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.cac.dme.adapter.utils.ContextCommonHolder;
import com.cac.dme.common.utils.JsonHelper;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.cac.dme.adapter.utils.BusinessUtil.getSortExpColumnName;

@RestController
@RequestMapping("/workbinMaterialMaintain")
@Slf4j
public class workbinMaterialMaintainRest {
    @Autowired
    private workbinMaterialMaintainService workbinMaterialMaintainservice;
    @Autowired
    private workbinMaterialMaintainDao workbinMaterialMaintainDao;

    /*缓存料箱物料信息维护查询*/
    @PostMapping("/workbinMaterialMaintainSearch")
    public ResponseMsg<QueryRespBean<HashMap>> workbinMaterialMaintainSearch(@RequestBody HashMap map) {
        ResponseMsg<QueryRespBean<HashMap>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);

        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), MsWorkbinBasicDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            HashMap searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<HashMap>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<HashMap> result = workbinMaterialMaintainservice.workbinMaterialMaintainSearch(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp());
       /* List<HashMap> result1 = workbinMaterialMaintainservice.workbinMaterialMaintainSearch(searchParams, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp());
        if (result1.size() == 0) {
            responseMsg.setRetCode("201").setMessage("未查询到数据").setResponseBody(result);
        } else responseMsg.setResponseBody(result);*/
        responseMsg.setResponseBody(result);
        return responseMsg;

    }

    /*缓存料箱物料信息维护新增*/
    @PostMapping("/workbinMaterialMaintainInsert")
    public ResponseMsg<String> workbinMaterialMaintainInsert(@RequestBody HashMap map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String user = (String) request.getSession().getAttribute("account");

        if ("".equals(map.get("groupCode")) || map.isEmpty() || "".equals(map.get("itemQty"))) {
            responseMsg.setMessage("参数输入有误，请检查！").setRetCode("201");
        }
        if (Objects.isNull(user)) {
            log.info("session过期，请重新登陆");
            responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        }
        map.put("user", user);
        map.put("IP", IP);
        //校验此图号是否已经存在 2023-12-12
        int cnt = workbinMaterialMaintainservice.checkItemExists(map);
        if(cnt>0){
            responseMsg.setMessage("改图号已经存在，不需要新增！").setRetCode("201");
            return responseMsg;
        }
        int workbin = workbinMaterialMaintainservice.workbinMaterialMaintainInsert(map);
        if (workbin == 1) {
            responseMsg.setRetCode("200").setMessage("新增成功！");
        } else {
            responseMsg.setRetCode("201").setMessage("新增失败");
        }
        return responseMsg;
    }

    /*缓存料箱物料信息维护修改*/
    @PostMapping("/workbinMaterialMaintainUpdate")
    public ResponseMsg<Map> workbinMaterialMaintainUpdate(@RequestBody HashMap map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String user = (String) request.getSession().getAttribute("account");

        if ("".equals(map.get("groupCode")) || map.isEmpty() || "".equals(map.get("itemQty"))) {
            responseMsg.setMessage("参数输入有误，请检查！").setRetCode("201");
        }
        //校验此图号是否已经存在 2023-12-12
        int cnt = workbinMaterialMaintainservice.checkItemExists(map);
        if(cnt>0){
            responseMsg.setMessage("改图号已经存在，不需要新增！").setRetCode("201");
            return responseMsg;
        }


        if (Objects.isNull(user)) {
            log.info("session过期，请重新登陆");
            responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        }
        map.put("user", user);
        map.put("IP", IP);
        if (map.get("msWorkbinRuleId") != null) {
            workbinMaterialMaintainservice.workbinMaterialMaintainUpdate(map);
            return responseMsg.setRetCode("200").setMessage("修改成功!");
        } else return responseMsg.setRetCode("201").setMessage("修改失败!");
    }

    /*缓存料箱物料信息维护删除*/
    @PostMapping("/workbinMaterialMaintainDelete")
    public ResponseMsg<Map> workbinMaterialMaintainDelete(@RequestBody HashMap map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap> ids = (List<HashMap>) map.get("msWorkbinRuleIds");
        if (ids.size() == 0) {
            return responseMsg.setRetCode("201").setMessage("请选中删除数据");
        }
        for (int i = 0; i < ids.size(); i++) {
            HashMap hashmap = new HashMap();
            hashmap.put("msWorkbinRuleId", ids.get(i));

            if (hashmap != null) {
                workbinMaterialMaintainservice.workbinMaterialMaintainDelete(hashmap);
                s++;
            } else f++;
        }
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("删除失败！");
            return responseMsg;
        }
        if (f == 0 && s != 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("删除成功！");
            return responseMsg;
        }
        if (s != 0 && f != 0) {
            responseMsg.setRetCode("202");
            responseMsg.setMessage("删除有失败项！");
            responseMsg.setResponseBody(reMsg);
            return responseMsg;
        }
        return responseMsg;
    }

    //xiaojian 5-19查询当前最大组号
    @PostMapping("/queryMaxGroup")
    public HashMap queryMaxGroup() {
        HashMap hashMap = new HashMap();
        HashMap map = workbinMaterialMaintainDao.queryMaxGroup();
        hashMap.put("retCode", "200");
        hashMap.put("retData", map);
        return hashMap;
    }
}
